package work.wiwf.web.model.sys.service.impl;

import com.gitee.fastmybatis.core.mapper.CrudMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import work.wiwf.web.model.sys.bean.SysUserBean;
import work.wiwf.web.model.sys.bean.entity.SysMenuEntity;
import work.wiwf.web.model.sys.bean.entity.SysUserEntity;
import work.wiwf.web.model.sys.bean.vo.SysRoleVo;
import work.wiwf.web.model.sys.bean.vo.SysUserVo;
import work.wiwf.web.model.sys.dao.SysUserMapper;
import work.wiwf.web.model.sys.service.SysTokenService;
import work.wiwf.web.model.sys.service.SysUserService;
import work.wiwf.web.service.impl.FastmbatisServiceImpl;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kehui
 */
@Service
public class SysUserServiceImpl extends FastmbatisServiceImpl<SysUserEntity, Integer> implements SysUserService {

    @Resource
    SysUserMapper sysUserMapper;

    @Autowired
    SysTokenService tokenService;

    @Override
    public CrudMapper<SysUserEntity, Integer> getMapper() {
        return sysUserMapper;
    }


    @Override
    public SysUserBean getUser(String username) {
        SysUserVo userInfo = sysUserMapper.getUserInfo(username);
        List<String> authorities = new ArrayList<String>();

        List<SysRoleVo> roles = userInfo.getRoles();
        for (SysRoleVo role : roles) {
            String roleCode = "ROLE_"+role.getRoleCode();
            authorities.add(roleCode);

            List<SysMenuEntity> menus = role.getMenus();
            for (SysMenuEntity menu : menus) {
                String menuCode = menu.getMenuCode();
                authorities.add(menuCode);
            }
        }

        // 生成token
        String token = tokenService.createToken();
        // 存储token
        tokenService.addTokenUser(token, userInfo, 12 * 60 * 60);

        SysUserBean sysUserBean = new SysUserBean(userInfo);
        sysUserBean.setAuthorities(authorities);
        sysUserBean.setToken(token);

        return sysUserBean;
    }
}
